package com.smashcrush.client.gwt;


import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.smashcrush.client.gwt.service.UserServiceAsync;
import com.smashcrush.client.gwt.util.WidgetUtil;

public class Login extends Composite {

	DockPanel dock;

	TextBox emailAddressTextBox;

	PasswordTextBox passwordTextBox;

	Button loginButton;

	Command loginCommand;

	public Login() {

		dock = new DockPanel();

		FlexTable table = new FlexTable();
		dock.add(table, DockPanel.CENTER);

		emailAddressTextBox = new TextBox();
		table.setWidget(0, 0, WidgetUtil.createLabel("E-mail Address"));
		table.setWidget(0, 1, emailAddressTextBox);

		passwordTextBox = new PasswordTextBox();
		table.setWidget(1, 0, WidgetUtil.createLabel("Password"));
		table.setWidget(1, 1, passwordTextBox);

		loginButton = new Button("Login");
		dock.add(loginButton, DockPanel.SOUTH);
		dock.setCellHorizontalAlignment(loginButton,
				HasHorizontalAlignment.ALIGN_CENTER);
		loginButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				login();
			}
		});
		
		Button test = new Button("Auto");
		dock.add(test, DockPanel.SOUTH);
		test.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				emailAddressTextBox.setText("joetoth@gmail.com");
				passwordTextBox.setText("kkkkkk");
				login();
			}
		});

		DecoratorPanel decorator = WidgetUtil.decorate(dock, "30%", "30%");
		initWidget(decorator);
	}

	public void setOnLoginCommand(Command command) {
		this.loginCommand = command;
	}

	private void login() {
System.out.println("login");
		String emailAddress = emailAddressTextBox.getValue();
		String password = passwordTextBox.getValue();

		UserServiceAsync.RPC.get().login(emailAddress, password,
				new AsyncCallback<String>() {

					@Override
					public void onSuccess(String result) {
						System.out.println("hiii"+result);
						if (result != null) {

							SecurityContext.get().setToken(result);
							loginCommand.execute();
						} else {
							Window.alert("Invalid Password");
						}
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}
				});
	}

}
